package com.dddframework.security.infras.config;

import com.dddframework.security.domain.auth.component.ResourceAuthExceptionEntryPoint;
import com.dddframework.security.domain.phone.component.PhoneAuthenticationFilter;
import com.dddframework.security.domain.phone.component.PhoneAuthenticationProvider;
import com.dddframework.security.domain.auth.service.IUserDetailService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 手机号登录配置入口
 *
 * @author zhouzx
 */
@Getter
@Setter
public class PhoneSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private AuthenticationEventPublisher eventPublisher;
    private AuthenticationSuccessHandler loginSuccessHandler;
    private IUserDetailService userService;

    @Override
    public void configure(HttpSecurity http) {
        PhoneAuthenticationFilter phoneAuthenticationFilter = new PhoneAuthenticationFilter();
        phoneAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        phoneAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        phoneAuthenticationFilter.setEventPublisher(eventPublisher);
        phoneAuthenticationFilter.setAuthenticationEntryPoint(new ResourceAuthExceptionEntryPoint());
        PhoneAuthenticationProvider phoneAuthenticationProvider = new PhoneAuthenticationProvider();
        phoneAuthenticationProvider.setUserService(userService);
        http.authenticationProvider(phoneAuthenticationProvider).addFilterAfter(phoneAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}